package com.fingard.dsp.bank.directbank.hkb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.directbank.fngrd01.util.StringHelper;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.MFSHelper;
import com.fingard.util.DateHelper;
import com.fingard.util.SmbFileUtil;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import static com.fingard.text.StringHelper.trimEndFileSp;

/**
 * @author Parker on 2019-08-08.
 * @version 1.0
 */
public class HKB01Transaction extends HKB01Base implements ITransaction {
    /**
     * 历史明细
     *
     * @param p_req7516
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        RetAtsTrans retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
        retAtsTrans.writeStart();
        String tmpRespCode = "";
        String tmpRespInfo = "";
        try {
            //起始日期
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
            //结束日期
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            while (tmpIntDateFrom <= tmpIntDateTo && StringHelper.isNullOrEmpty(tmpRespCode)) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //当是跨月查询时，先查询起始日期到月末日期记录，再查询月末后一天日期到结束日期记录
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }
                //拼接报文
                //非公有参数
                XmlTextWriter xmlTextWriter = new XmlTextWriter();
                //拼接请求报文头
                HKB01Header header = new HKB01Header();
                header.tr_code = "200110";//交易码
                header.req_no = p_req7516.reqHeader.reqSeqID;
                writeCommonHeader(xmlTextWriter, header);
                //拼接请求报文体
                xmlTextWriter.writeStartElement("body");
                xmlTextWriter.writeElementString("acno", p_req7516.actNum);//帐号
                xmlTextWriter.writeElementString("cur_code", convertCurToBank(p_req7516.actCur));//币种
                xmlTextWriter.writeElementString("start_date", Format.Date8Format.format(tmpCalendarFrom.getTime()));//开始时间
                xmlTextWriter.writeElementString("end_date", Format.Date8Format.format(tmpClndrStepTo.getTime()));//结束时间
                xmlTextWriter.writeEndDocument();

                //发送请求报文
                String[] resutlt = sendToBank(xmlTextWriter.toXmlString());
                //处理响应报文
                if (resutlt[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(resutlt[1].substring(resutlt[1].indexOf("<ap>")), tmpSbMsg);
                    if (tmpBkReader != null) {
                        String succFlag = tmpBkReader.getFirstText("/ap/head/succ_flag");
                        String respCode = tmpBkReader.getFirstText("/ap/head/ret_code");
                        String respInfo = tmpBkReader.getFirstText("/ap/head/ret_info");
                        if ("0".equals(succFlag) && "0000".equals(respCode)) {//交易成功
                            String totalNum = tmpBkReader.getFirstText("/ap/body/record_num");//总数
                            String valueNum = tmpBkReader.getFirstText("/ap/body/field_num");//字段数
                            String serial_recode = null;
                            if ("1".equals(tmpBkReader.getFirstText("/ap/head/file_flag"))) {
                                String tmpBatchFileName = tmpBkReader.getFirstText("/ap/body/file_name");
                                //下载共享目录批量查询文件
                                String downloadFilePath = trimEndFileSp(bankFront.bkTransFolder) + File.separator;//共享目录路径
                                String p_FileFullPath = getTempFileDirectory() + File.separator + Format.Time6Format.format(new Date());//下载到的本地路径
                                StringBuilder p_sb = new StringBuilder();
                                if (SmbFileUtil.smbDownloadInChar(p_FileFullPath, downloadFilePath, tmpBatchFileName, p_sb) == 1) {
                                    WriteBankLogLn("共享目录文件，位于：" + downloadFilePath);
                                    WriteBankLogLn("文件下载成功，位于：" + p_FileFullPath);
                                    p_FileFullPath = p_FileFullPath + File.separator + tmpBatchFileName;
                                    serial_recode = FileHelper.readFileText(p_FileFullPath, getCharset());
//                                        tmpDataMFS = FileHelper.readFileText("E:\\工作1\\HSBTransmitter\\Temp\\"+tmpBatchFileName, getCharset());
                                } else {
                                    retAtsTrans.writeRespCode("-1");
                                    retAtsTrans.writeRespInfo(p_sb.toString());
                                    retAtsTrans.writeEnd();
                                    return retAtsTrans;
                                }
                            } else {
                                serial_recode = tmpBkReader.getFirstText("/ap/body/serial_recode");//字段域
                            }
                            if (!"0".equals(totalNum) && !"0".equals(valueNum) && !StringHelper.isNullOrEmpty(serial_recode)) {
                                StringBuilder tmpSbLog = new StringBuilder();
                                ArrayList<String[]> tmpArrayList = MFSHelper.getTextArray(serial_recode, "|", Integer.parseInt(valueNum), Integer.parseInt(totalNum) + 1, tmpSbLog);
                                if (tmpSbLog.length() == 0) {
                                /*0平台流水号|1账号|2货币码|3交易日期|4交易时间交易日期|5主机流水号|6交易行号|7户名|8对方账号|9对方货币码|10对方账号户名|
//                              11对方账号开户行|12对方行号|13交易类别|14钞汇标志|15他行标志|16同城异地标志|17手续费|18交易来源|19发生额标志|
//                              20被冲销流水号|21原交易日期|22现转标志|23借贷标志|24交易金额|25余额|26上笔余额|27冻结金额|28凭证种类|29凭证批次号|
//                              30凭证号码|31交易码|32柜员号|33传票号|34摘要|35附言|36交易时间戳|37备注字段一|38备注字段二|39交易行名|40、行号（C12）|41、打印次数（N10）|42支付金额|43收入金额|*/
                                    for (int i = 1; i < tmpArrayList.size(); i++) {
                                        String[] tmpEachArr = tmpArrayList.get(i);
                                        RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                        tmpRetDetail.actArea = p_req7516.actArea;//银行地区区域码
                                        tmpRetDetail.actNum = p_req7516.actNum;//银行账号
                                        tmpRetDetail.recAccNum = tmpEachArr[8].trim();//对方账号
                                        tmpRetDetail.recAccName = tmpEachArr[10].trim();//对方户名
                                        String tmpRecBank = com.fingard.text.StringHelper.convertToDBC(tmpEachArr[11]).trim();
                                        tmpRetDetail.recAccBank = tmpRecBank;//对方开户银行
                                        //交易日期
                                        if (tmpEachArr[3].length() == 8) {
                                            tmpRetDetail.tranDate = tmpEachArr[3].substring(0, 4) + "-" + tmpEachArr[3].substring(4, 6) + "-" + tmpEachArr[3].substring(6, 8);
                                        }
                                        //交易时间
                                        if (tmpEachArr[4].length() < 2) {
                                            tmpRetDetail.tranTime = tmpRetDetail.tranDate + " 00:00:00";
                                        } else if (tmpEachArr[4].length() >= 14) {
                                            tmpRetDetail.tranTime = tmpEachArr[4].substring(0, 4) + "-" + tmpEachArr[4].substring(4, 6) + "-" + tmpEachArr[4].substring(6, 8) + " " + tmpEachArr[4].substring(8, 10) + ":" + tmpEachArr[4].substring(10, 12) + ":" + tmpEachArr[4].substring(12, 14);
                                        } else {
                                            tmpRetDetail.tranTime = tmpRetDetail.tranDate + " " + tmpEachArr[4].substring(0, 2) + ":" + tmpEachArr[4].substring(2, 4) + ":" + tmpEachArr[4].substring(4, 6);
                                        }
                                        tmpRetDetail.valueDate = tmpRetDetail.tranDate;//起息日期
                                        tmpRetDetail.tranAmt = tmpEachArr[24];//交易金额
                                        tmpRetDetail.accBal = tmpEachArr[25];//账号余额
                                        tmpRetDetail.postTimestamp = tmpEachArr[36];//时间戳
                                        if ("C".equals(tmpEachArr[23])) {
                                            tmpRetDetail.cdFlag = "2";//借贷标志
                                        } else if ("D".equals(tmpEachArr[23])) {
                                            tmpRetDetail.cdFlag = "1";//借贷标志
                                        }
                                        tmpRetDetail.billType = tmpEachArr[28];//票据类型
                                        tmpRetDetail.billNum = tmpEachArr[30];//票据号码
                                        tmpRetDetail.usage = tmpEachArr[34];//用途(摘要)
//                                            tmpRetDetail.abstr = "";//对账码(交易码)
//                                            tmpRetDetail.payCode = "";//支付信息
                                        tmpRetDetail.comment = tmpEachArr[35];//备注(附言)
//                                            tmpRetDetail.askNumber = "";//支付流水号？？
                                        tmpRetDetail.reqBatchNO = tmpEachArr[29];//支付批号(29凭证批次号)
                                        tmpRetDetail.cur = this.convertCurToATS(tmpEachArr[2]);//币种
//                                            tmpRetDetail.seqId = "";//序号
//                                            tmpRetDetail.isCollection = "";//是否现金池
                                        tmpRetDetail.originator = tmpEachArr[0];//银行返回流水号
                                        nodeAnalysic(tmpEachArr, tmpRetDetail, getCharset());
                                        retAtsTrans.writeRetDetail(tmpRetDetail);
                                    }
                                } else {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = tmpSbLog.toString();
                                }
                            } else {
                                tmpRespCode = "0";
                                tmpRespInfo = "该时间段的总明细条数为0";
                            }
                        } else {//查询异常
                            tmpRespCode = "-1";
                            tmpRespInfo = respInfo;
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();
                        break;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = resutlt[1];
                    break;
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception ex) {
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            ex.printStackTrace();
            WriteBankLogLn("查询明细异常:" + ex);
        }
        if ("-1".equals(tmpRespCode)) {
            retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
            retAtsTrans.writeStart();//写返回ATS的统一头部信息
            retAtsTrans.writeRespCode(tmpRespCode);
            retAtsTrans.writeRespInfo(tmpRespInfo);
        } else if (retAtsTrans.getWrittenRdCount() == 0) {
            retAtsTrans.writeRespInfo("交易为空");
            retAtsTrans.writeRespCode("0");
        }
        retAtsTrans.writeEnd();
        return retAtsTrans;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        //通用历史余额查询
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;
        tmpReq7516.dateTo = tmpStrToday;
        return d_7516_HisTrans(tmpReq7516);
    }
}
